#!/usr/bin/python
import os
import time
from datetime import datetime
#import commands
import sys

def logit(message):
    log.write(str(time.ctime()))
    log.write("\t",message,"\n")

class Ddict(dict):
    def __init__(self, default=None):
        self.default = default

    def __getitem__(self, key):
        if not self.has_key(key):
            self[key] = self.default()
        return dict.__getitem__(self, key)


watchpath = "/root/Videos"
email = "emailaddress"
prowl = "no"
#log file
logfile = "/root/.handbrakedirwatch/log"
log = open(logfile,"a")

#see if handbrake is running
#os.system("ps auxww|grep -i handbrake")
h = os.popen("ps auxww|grep -i handbrakecli|grep -v \"ps auxww\"")
if h:
    logit("handbrake is currently running - will not try to run further")

#get list of files that were in the dir and converted
if os.path.isfile("~/.handbrakedirwatch/dirlist"):
    list = open("~/.handbrakedirwatch/dirlist", "r")
    dlist = {}
    for l in list.readlines():
        logit("getting history of files that have been seen in ",watchpath)
        f = l.split()
        flist[f[0]]=f[1]

#if there is a file that needs to be converted, convert it
for names in flist:
    if flist[names] == new:
        logit("converting ",names," to iphone format")
        convert_string = "nohup HandBrakeCLI -Z \"iPhone & iPod Touch\" -i ~/Download/",input_name," -o ~/Videos/",output_name,".m4v &"
        discard = os.popen(convert_string)
        logit("output for ",output_name," is in nohup file")
        sys.exit()
#see if there is any files that havnt been converted yet
current = os.popen('ls -1 ' + watchpath)
clist = {}
for c in current.readlines():
    print c.rstrip()
    clist[c]="looking"
    if flist[c]:
        if flist[c] == "done":
            clist[c] = "done"
        elif flist[c] == "working":
            print "here"
    else:
        logit("marking ",c," as new") 
        clist[c] = "new"
        flist[c] = "new"

for name in clist:
    if clist[name] == new:
        


#close log
log.close()

